package com.sky.controller.user;

import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 地址簿相关接口
 */
@RestController
@RequestMapping("/user/addressBook")
@Api(tags = "地址簿相关接口")
@Slf4j
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;

    /**
     * 用户新增地址
     * @param addressBook
     * @return
     */
    @PostMapping("")
    @ApiOperation("用户端新增地址")
    public Result<String> addAddressBook(@RequestBody AddressBook addressBook){
        log.info("用户新增地址：{}",addressBook);
        addressBookService.add(addressBook);
        return Result.success();
    }

    /**
     * 用户修改地址
     * @param addressBook
     * @return
     */
    @PutMapping("")
    @ApiOperation("修改地址")
    public Result<String> updateAddressBook(@RequestBody AddressBook addressBook){
        log.info("用户修改地址：{}",addressBook);
        addressBookService.update(addressBook);
        return Result.success();
    }

    /**
     * 用户删除地址
     * @param id
     * @return
     */
    @DeleteMapping("")
    @ApiOperation("删除地址")
    public Result<String> deleteAddressBook(Long id){
        log.info("用户删除地址,id={}",id);
        addressBookService.delete(id);
        return Result.success();
    }

    /**
     * 列出用户地址
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("列出地址")
    public Result<List<AddressBook>> listAddressBook(){
        log.info("列出用户地址");
        List<AddressBook> list=addressBookService.list();
        return Result.success(list);
    }

    /**
     * 用户设置默认地址
     * @return
     */
    @PutMapping("/default")
    @ApiOperation("设置默认地址")
    public Result<String> setDefault(@RequestBody AddressBook addressBook){
        log.info("设置默认地址：id={}",addressBook);
        addressBookService.setDefault(addressBook.getId());
        return Result.success();
    }

    /**
     * 根据id获取地址
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation("根据id获取地址")
    public Result<AddressBook> getAddressBookById(@PathVariable Long id){
        log.info("根据id获取地址");
        AddressBook addressBook=addressBookService.getAddressBookById(id);
        return Result.success(addressBook);
    }

    @GetMapping("/default")
    @ApiOperation("获取默认地址")
    public Result<AddressBook> getDefault(){
        log.info("获取默认地址");
        AddressBook addressBook=addressBookService.getDefault();
        if(addressBook==null){
            return Result.error("没有查询到默认地址");
        }
        return Result.success(addressBook);
    }
}
